import json

from .func import stock_out, stock_in, cancel_stock_occupy, syncSkuFromPDC
from flask_restful import Resource, request

from extensions import rest_api, db
from ...models import Setting
from ...constants import ENABLE_DTC_STOCK_ASYNC
# from ...tasks.stock_update_task import stock_in_task, stock_out_task, cancel_stock_occupy_task

__all__ = ['SyncSkuFromPDCApi']

def is_aysnc():
    settings = Setting.query.filter(Setting.cfg_key == ENABLE_DTC_STOCK_ASYNC).first()
    if settings and settings.cfg_value in (1, "1"):
        return True
    return False


class UpdateStock(Resource):

    def post(self):

        kwargs = json.loads(request.data.decode())
        if not isinstance(kwargs, list):
            kwargs = [kwargs]
        ret = {"code": 200, "msg": ""}
        msg = "success"
        for kwarg in kwargs:
            business_type = kwarg.get('business_type')
            try:
                if business_type == 2:
                    if is_aysnc():
                        # stock_out_task(kwarg)
                        print()
                    else:
                        stock_out(kwarg)
                    continue
                elif business_type == 1:
                    if is_aysnc():
                        # stock_in_task(kwarg)
                        print()
                    else:
                        stock_in(kwarg)
                    continue
                elif business_type == 3:
                    if is_aysnc():
                        # cancel_stock_occupy_task(kwarg)
                        msg = '组合商品，未处理'
                    else:
                        cancel_stock_occupy(kwarg)
                    continue
            except Exception as e:
                db.session.rollback()
                return {"code": 500, "msg": "{}".format(e)}
        ret.update({"msg": msg})
        return ret


class SyncSkuFromPDCApi(Resource):

    def get(self):
        ret = {"code": 200, "msg": "", "data": ""}
        return ret

    def post(self):

        kwargs = json.loads(request.data.decode())
        # print(kwargs)
        isCombGoods = kwargs.get('isCombGoods')
        ret = {"code": 200, "msg": ""}
        code = 200

        msg = "success"
        try:
            if isCombGoods == 2:
                # 单品处理
                code, msg = syncSkuFromPDC(kwargs.get('obj'))
            elif isCombGoods == 1:
                # 组合商品不处理
                # print('组合商品不处理')
                msg = '组合商品，未处理'
                pass
        except Exception as e:
            db.session.rollback()
            return {"code": 500, "msg": "{}".format(e)}
        ret.update({"code": code, "msg": msg})
        return ret

rest_api.add_resource(UpdateStock, "/update_stock/")
rest_api.add_resource(SyncSkuFromPDCApi, "/syncSkuFromPDC/")
